package com.reebake.ideal.storage.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import com.reebake.ideal.storage.entity.BytesMultipartFile;
import com.reebake.ideal.storage.entity.FileInfoDTO;
import com.reebake.ideal.storage.entity.FileUploadRequestDTO;
import com.reebake.ideal.storage.properties.StorageProperties;
import com.reebake.ideal.storage.util.StorageUtil;
import com.reebake.ideal.storage.vo.Base64DecodedMultipartFile;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/storage/file")
public class FileUploadController {
    @Autowired
    private StorageProperties storageProperties;
    @Autowired
    private FileStorageService fileStorageService;//注入实列

    @PostMapping(value = "/upload-image-data")
    public FileInfoDTO upload(@RequestBody FileUploadRequestDTO file) {
        Base64DecodedMultipartFile multipartFile = (Base64DecodedMultipartFile) Base64DecodedMultipartFile.base64ToMultipart(file.getFile());
        String platform = file.getPlatform();
        String path = file.getPath();
        String originalFilename = file.getOriginalFilename();
        FileInfo fileInfo = fileStorageService.of(multipartFile)
                .setPlatform(StrUtil.isNotBlank(platform), platform)
                .setPath(StrUtil.isNotBlank(path), path)
                .setOriginalFilename(StrUtil.isNotBlank(originalFilename), originalFilename)
                .upload();
        return StorageUtil.toFileInfoDTO(fileInfo);
    }

    @PostMapping("/upload")
    public FileInfoDTO upload(@RequestParam(required = false) String platform
            , @RequestParam(required = false) String path
            , @RequestParam(required = false) String originalFilename
            , @RequestParam(required = false) String content
            , @RequestParam(required = false) String contentType
            , MultipartFile file) {
        if(StrUtil.isNotBlank(content)){
            byte[] bytes = Base64.decode(content);
            file = new BytesMultipartFile(originalFilename, contentType, bytes);
        }
        FileInfo fileInfo = fileStorageService.of(file)
                .setPlatform(StrUtil.isNotBlank(platform), platform)
                .setPath(StrUtil.isNotBlank(path), path)
                .setOriginalFilename(StrUtil.isNotBlank(originalFilename), originalFilename)
                .upload();
        return StorageUtil.toFileInfoDTO(fileInfo);
    }
}
